package com.gitee.huanminabc.utils_tools.log_extend.restTemplate;

import com.gitee.huanminabc.jcommon.base.SnowIdUtil;
import com.gitee.huanminabc.jcommon.str.StringUtil;
import com.gitee.huanminabc.utils_tools.log_extend.Constants;
import com.gitee.huanminabc.utils_tools.log_extend.LogTraceContextHolder;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.IOException;

/**
 * @author 胡安民
 *
 * RestTemplate 拦截器，trace放入header
 */
public class RestTemplateLogTraceInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException {
        String traceId = LogTraceContextHolder.get();
        if (StringUtil.isEmpty(traceId)){
            traceId = SnowIdUtil.uniqueLongHex();
        }
        httpRequest.getHeaders().add(Constants.LOG_TRACE_ID_HEADER, traceId);
        return clientHttpRequestExecution.execute(httpRequest, bytes);
    }
}
